import { useCallback, useEffect, useState } from 'react';
import { View, Text, Image } from '@tarojs/components'
import PageContainer from '@/components/PageContainer'
import i18n from "i18n-js"
import { GStyleSheet } from '@/utils/DarkMode'
import { GButton } from "@/components/GButton"
import Taro, { useDidShow } from '@tarojs/taro';
import { observer } from 'mobx-react-lite';
import FlexScrollView from '@/components/FlexScrollView'
import Alert from '@/components/Alert'
import Toast from '@/utils/Toast';
import deviceDetailModel from '@/models/deviceDetail';
import SchduleItem from './components/SchduleItem';
import { goToDetialPage } from './utils/detailModel'
import { ISchedule, setDevice, hanldeServiceSchedule } from './utils/tool'
import { getScheduleList, deleteSchedule, editScheduleEnabled } from './utils/scheduleApi'


// const list: ISchedule[] = [];


const TimingScreen = () => {

  const [list, setList] = useState<ISchedule[]>([])
  const [delSchedule, setDelSchedule] = useState<ISchedule>()

  const queryData = useCallback(async () => {
    const res = await getScheduleList({ did: deviceDetailModel.device!.did!, limit: 200, skip: 0 })
    if (res.success) {
      if (res.data) {
        const arr = res.data.map(i => hanldeServiceSchedule(i))
        setList(arr)
      }
    }
  }, [])

  useEffect(() => {
    setDevice(deviceDetailModel.device!)
    queryData()
  }, [])

  const styles = dstyles.useDynamicStyle();

  useDidShow(() => {
    queryData()
  })

  const goToSetTimer = useCallback(() => {
    goToDetialPage({})
  }, [])

  const editScheduleEnable = useCallback((schdule: ISchedule, enable: boolean) => {
    const newList = [...list];
    schdule.enabled = enable;
    setList(newList);
    editScheduleEnabled(schdule, enable).then(data => {
      // 临时处理，正确做法参考智家，修正到正确的时间
      if (data.success) {

      } else {
        try {
          const timeExpired = JSON.stringify(data.err.response).indexOf('date time expired') !== -1
          if (timeExpired) {
            Taro.showToast({
              title: "时间已过期",
              icon: 'error'
            })
          }
          const backList = [...list];
          schdule.enabled = !enable;
          setList(backList);
        } catch (error) {
          
        }
      }
    }).catch(err => {
      console.log('editScheduleEnabled', err.err.response)
    });
  }, [list])

  const showDeleteAlert = useCallback((schdule: ISchedule) => {
    setDelSchedule(schdule)
  }, [])

  const hienDeleteAlert = useCallback(() => {
    setDelSchedule(undefined)
  }, [])

  const deleteScheduleRequest = useCallback(async () => {
    hienDeleteAlert()
    Toast.showLoading({ content: '' })
    const res = await deleteSchedule(delSchedule!)
    queryData()
    Toast.hideLoading()
    if (res.success) {
      Toast.success('删除成功')
    } else {
      Toast.error('删除失败')
    }

  }, [delSchedule, queryData, hienDeleteAlert])

  return (
    <PageContainer title='定时'>
      <View style={{ ...styles.container, justifyContent: list.length > 0 ? 'space-between' : 'center' }}>
        {
          list.length > 0 && (
            <FlexScrollView id='schedule-list'>
              {
                list.map(schdule => <SchduleItem key={schdule.id} schedule={schdule} onDelete={showDeleteAlert} onEdit={editScheduleEnable} />)
              }
            </FlexScrollView>
          )
        }
        <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>
          {
            list.length === 0 && <Image
              mode='aspectFit'
              style={{ width: 92, height: 92, marginBottom: 12 }}
              src='https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/479438/media/%E7%BC%BA%E7%9C%81%E9%A1%B5_%E6%9A%82%E6%97%A0%E8%AE%A1%E5%88%92%E5%A4%87%E4%BB%BD%402x_1667140019174.png'
            />
          }
          <GButton
            primary
            text={i18n.t("ADD_TIMER")}
            onPress={goToSetTimer}
          />
        </View>
      </View>
      <Alert
        title={i18n.t("DELETE_SCHEDULE_TIPS")}
        visible={!!delSchedule}
        onCancel={hienDeleteAlert}
        onConfirm={deleteScheduleRequest}
      />
    </PageContainer>
  )
}

const dstyles = GStyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    alignItems: 'center',
  }
});

export default observer(TimingScreen)
